package cn.wsn2018.tools.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by NZX on 2018/12/24.
 */
public class TestUtil {
    public static String sendParam(String uri,String paramName,String data,String charset){
        String result = "";
        PrintWriter out =null;
        InputStream in = null;
        try {
            URL url=new URL(uri);

            HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
            urlcon.setDoInput(true);
            urlcon.setDoOutput(true);
            urlcon.setUseCaches(false);
            urlcon.setRequestMethod("GET");
            //urlcon.setRequestProperty("contentType", "utf-8");

            urlcon.connect();
            out = new PrintWriter(urlcon.getOutputStream());

            data = URLEncoder.encode(data, "utf-8");
            out.print(paramName+"="+data);
            out.flush();
            in = urlcon.getInputStream();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(
                    in, charset));
            StringBuffer bs = new StringBuffer();
            String line ="" ;
            while ((line = buffer.readLine()) !=null ) {
                bs.append(line);
            }
            result = bs.toString();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("[请求异常][地址：" + uri + "][参数：" + data + "][错误信息："
                    + e.getMessage() + "]");
        } finally {
            try {
                if ( null != in)
                    in.close();
                if ( null != out)
                    out.close();
            } catch (Exception e2) {
                e2.printStackTrace();
                System.out.println("[关闭流异常][错误信息：" + e2.getMessage() + "]");
            }
        }

        return result;

    }
}
